package cn.edu.zafu.bigdata.x.wgj.g;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileManipulation {

    // 将文本写入文件的方法
    public static void writeToFile(String fileName, String content) {
        try {
            File file = new File("files/" + fileName);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件中读取内容并打印到控制台的方法
    public static void readFromFile(String fileName) {
        try {
            File file = new File("files/" + fileName);
            if (!file.exists()) {
                System.out.println("文件不存在！");
                return;
            }

            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine())!= null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入学号：");
        String studentId = scanner.nextLine();

        System.out.println("请输入要保存的文本内容：");
        String inputText = scanner.nextLine();

        // 写入文件
        writeToFile(studentId + ".txt", inputText);

        // 读取并显示文件内容
        readFromFile(studentId + ".txt");

        scanner.close();
    }
}